/*
 * @Author: wusd
 * @Date: 2022-06-15 09:39:58
 * @LastEditors: wusd
 * @LastEditTime: 2022-06-15 14:59:34
 * @Description:
 *
 */
import Router from '@/router'
import stroage from '@/untils/stroage'
import { MenueItem } from 'types/common'

export default {
  state: {
    menue: [] as Array<MenueItem>,
    currentMenue: {} as MenueItem,
    tabsList: []
  },
  mutations: {
    closeTab(state: { tabsList: any[] }, val: { name: any }) {
      const result = state.tabsList.findIndex(item => item.name === val.name)
      state.tabsList.splice(result, 1)
    },
    setMenue(state: { menue: any }, val: string) {
      state.menue = val
      stroage.set('menue', val)
    },
    getMenue(state: { menue: string | never[] }) {
      state.menue = stroage.get('menue') || []
    },
    selectMenu(state: { menue: any; currentMenue: any; tabsList: any[] }, val: { path: any; name: string }) {
      // 判断是菜单对象还是路由名称,是路由名称则先检索菜单对象
      if (val.path) {
        // 在菜单列表中递归查询当前路由名称的对象
        const selectMenu = (name: string, menus: any[], callback: { (menue: any): any; (arg0: any): void }) => {
          menus.forEach(menue => {
            if (menue.name === name) {
              callback(menue)
            } else if (menue?.children?.length) {
              selectMenu(name, menue.children, callback)
            }
          })
        }
        selectMenu(val.name, state.menue, (menue: any) => (val = menue))
      }
      if (val.name !== 'home' && val.name) {
        state.currentMenue = val
        const result = state.tabsList.findIndex(item => item.name === val.name)
        result === -1 ? state.tabsList.push(val) : ''
      } else {
        state.currentMenue = null
      }
    }
  },
  actions: {
    async addMenue(obj: { state: any }) {
      const state = obj.state
      function fixRouter(arr: string | any[]) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].pageUrl) {
            menue.push({
              ...arr[i],
              component: () => import(`@/view${arr[i].pageUrl}`)
            })
          }
          if (arr[i]?.children?.length > 0) {
            fixRouter(arr[i].children)
          }
        }
      }
      const res = JSON.parse(JSON.stringify(state.menue))
      const menue: any[] = []
      fixRouter(res)
      Router.$addRoutes([
        {
          //主页面
          path: '/manage/main',
          name: 'manage_mian',
          component: () => import('@/view/main/manage.vue'),
          children: menue
        }
      ])
    }
  }
}
